package com.dify.knowledge.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dify.knowledge.dto.UnansweredQuestionDTO;
import com.dify.knowledge.entity.ManualAnswer;
import com.dify.knowledge.service.ScheduledTaskService;
import com.dify.knowledge.service.UnansweredQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 未解答问题控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/unanswered")
public class UnansweredQuestionController {

    private final UnansweredQuestionService unansweredQuestionService;
    private final ScheduledTaskService scheduledTaskService;

    public UnansweredQuestionController(UnansweredQuestionService unansweredQuestionService,
                                         ScheduledTaskService scheduledTaskService) {
        this.unansweredQuestionService = unansweredQuestionService;
        this.scheduledTaskService = scheduledTaskService;
    }

    /**
     * 获取未解答问题列表
     * 
     * @param page 页码（默认1）
     * @param size 每页大小（默认10）
     * @return 分页的未解答问题列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getUnansweredQuestions(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        log.info("获取未解答问题列表，页码：{}，每页大小：{}", page, size);
        
        Page<UnansweredQuestionDTO> result = unansweredQuestionService.getUnansweredQuestions(page, size);
        
        Map<String, Object> response = new HashMap<>();
        response.put("records", result.getRecords());
        response.put("total", result.getTotal());
        response.put("current", result.getCurrent());
        response.put("size", result.getSize());
        response.put("pages", result.getPages());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 提交人工解答
     * 
     * @param questionId 未解答问题ID
     * @param request 解答请求
     * @return 创建的人工解答
     */
    @PostMapping("/{questionId}/answer")
    public ResponseEntity<Map<String, Object>> submitAnswer(
            @PathVariable Long questionId,
            @RequestBody SubmitAnswerRequest request) {
        
        log.info("提交人工解答，问题ID：{}，用户ID：{}", questionId, request.getUserId());
        
        // 验证请求参数
        if (request.getAnswer() == null || request.getAnswer().trim().isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "解答内容不能为空"));
        }
        
        if (request.getUserId() == null) {
            return ResponseEntity.badRequest().body(Map.of("error", "用户ID不能为空"));
        }
        
        ManualAnswer answer = unansweredQuestionService.submitManualAnswer(
                questionId, 
                request.getAnswer(), 
                request.getUserId()
        );
        
        Map<String, Object> response = new HashMap<>();
        response.put("answerId", answer.getId());
        response.put("message", "解答提交成功");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 对人工解答进行评分
     * 
     * @param answerId 解答ID
     * @param request 评分请求
     * @return 评分结果
     */
    @PostMapping("/answer/{answerId}/rate")
    public ResponseEntity<Map<String, Object>> rateAnswer(
            @PathVariable Long answerId,
            @RequestBody RateAnswerRequest request) {
        
        log.info("对解答评分，解答ID：{}，用户ID：{}，评分：{}", answerId, request.getUserId(), request.getRating());
        
        // 验证请求参数
        if (request.getUserId() == null) {
            return ResponseEntity.badRequest().body(Map.of("error", "用户ID不能为空"));
        }
        
        if (request.getRating() == null || 
            (!request.getRating().equals("useful") && !request.getRating().equals("useless"))) {
            return ResponseEntity.badRequest().body(Map.of("error", "评分必须是useful或useless"));
        }
        
        boolean isUseful = request.getRating().equals("useful");
        
        unansweredQuestionService.rateAnswer(answerId, request.getUserId(), isUseful);
        
        Map<String, Object> response = new HashMap<>();
        response.put("message", "评分成功");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取某问题的所有解答
     * 
     * @param questionId 未解答问题ID
     * @return 解答列表
     */
    @GetMapping("/{questionId}/answers")
    public ResponseEntity<Map<String, Object>> getAnswers(@PathVariable Long questionId) {
        log.info("获取问题的所有解答，问题ID：{}", questionId);
        
        List<ManualAnswer> answers = unansweredQuestionService.getAnswersByQuestionId(questionId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("answers", answers);
        response.put("count", answers.size());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 手动触发同步高分答案到Dify知识库
     * 
     * @return 同步结果
     */
    @PostMapping("/sync-to-knowledge-base")
    public ResponseEntity<Map<String, Object>> syncToKnowledgeBase() {
        log.info("手动触发同步高分答案到Dify知识库");
        
        try {
            ScheduledTaskService.SyncResult result = scheduledTaskService.syncTopAnswersToKnowledgeBase();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "同步完成");
            response.put("syncedCount", result.getSyncedCount());
            response.put("failedCount", result.getFailedCount());
            response.put("totalCount", result.getTotalCount());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("同步高分答案到知识库失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 提交解答请求DTO
     */
    public static class SubmitAnswerRequest {
        private String answer;
        private Long userId;

        public String getAnswer() {
            return answer;
        }

        public void setAnswer(String answer) {
            this.answer = answer;
        }

        public Long getUserId() {
            return userId;
        }

        public void setUserId(Long userId) {
            this.userId = userId;
        }
    }

    /**
     * 评分请求DTO
     */
    public static class RateAnswerRequest {
        private String rating; // "useful" 或 "useless"
        private Long userId;

        public String getRating() {
            return rating;
        }

        public void setRating(String rating) {
            this.rating = rating;
        }

        public Long getUserId() {
            return userId;
        }

        public void setUserId(Long userId) {
            this.userId = userId;
        }
    }
}
